
//
//  DiscoverMCircleListViewController.m
//  HAODE
//
//  Created by panquanReabam.com on 15/9/14.
//  Copyright (c) 2015年 reabam.com. All rights reserved.
//
#import "DiscoverMCircleListViewController.h"
#import "RDVTabBarController.h"
#import "MCircleListCell.h"
#import "MCirclemodel.h"
#import "UIImageView+WebCache.h"

#import "HttpRequest.h"
#import "TheLoginViewController.h"
#import "HAODEsingleton.h"
#import "MJRefresh.h"
#import "DiscoverMCircleDetailViewController.h"
#import "DiscoverMCircleAddViewController.h"
@interface DiscoverMCircleListViewController ()<UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate>
@property (strong, nonatomic)UITableView *tableView;
@property (nonatomic, strong) UIImageView * allImageBtn;
@property(nonatomic,strong)NSString*sta;
@end

@implementation DiscoverMCircleListViewController{
    int index;
    NSString * hasNext;
    NSString *nextIndex;
    NSMutableArray *allComment;
    NSMutableArray *amt;
    NSMutableArray *detail;
    NSMutableArray *provinceName;
    NSMutableArray *cityName;
    NSMutableArray *status;
    NSMutableArray*imageUrlFull;
    NSMutableArray *time;
    NSMutableArray *reqId;
    NSMutableArray *address;
    NSMutableArray *userName;
    HAODEsingleton*commdity;
    UIButton*sat;
    UIButton*sat1;
    UIButton*sxuan;
    int tapImageCount;
    int pageNumber;
    MJRefreshHeaderView* _header;
    MJRefreshFooterView* _footer;
    NSMutableArray*arr;
    NSString*TotalCount;
    UIButton*diseview;
    UIView*view;
    BOOL saveAccount;
    UILabel* noLabel;
    NSMutableArray*code;
    NSMutableArray*content1;
}
- (void)viewDidDisappear:(BOOL)animated

{
    
    [super viewDidDisappear:animated];
    
    
    
    self.navigationController.delegate = nil;
    
}
-(void)BackAction:(UIButton *)sender{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.delegate = self;
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@""] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage =[[UIImage alloc] init];
    
    [[self rdv_tabBarController] setTabBarHidden:YES];
    self.navigationController.navigationBarHidden = NO;
        self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    [self setup];
 

    
    UIButton*sxBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 0.0,  60/2, 60/2)];
    [sxBtn setImage:[UIImage imageNamed:@"fabiao"] forState:UIControlStateNormal];
    [sxBtn addTarget:self action:@selector(addProduct:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* myBtnBtn = [[UIBarButtonItem alloc] initWithCustomView:sxBtn];
    self.navigationItem.rightBarButtonItem = myBtnBtn;
    

    UIView *titleView = [[UIView alloc] init] ;
    titleView.frame = CGRectMake(0, 0, 150, 44);

    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.frame = CGRectMake(0, 10, 150, 20);
    self.titleLabel.font = [UIFont systemFontOfSize:tetlefot];
    self.titleLabel.backgroundColor = [UIColor clearColor];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.textColor = [UIColor blackColor];
    [titleView addSubview:self.titleLabel];

    self.navigationItem.titleView = titleView;

    UIButton* xuanxiang=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 150,44 )];
    [xuanxiang addTarget:self action:@selector(add:) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:xuanxiang];
    UIButton*sxBtn111 = [[UIButton alloc] initWithFrame:CGRectMake(120, 13.0,  15, 15)];
    [sxBtn111 setImage:[UIImage imageNamed:@"lusejiantou"] forState:UIControlStateNormal];
    [sxBtn111 addTarget:self action:@selector(add:) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:sxBtn111];
    saveAccount=YES;
    self.titleLabel.text = @"商户圈";

}
-(void)closeKeyBoad
{
    saveAccount=YES;
    [diseview removeFromSuperview];
    [view removeFromSuperview];
    [diseview removeFromSuperview];
}
-(void)add:(UIButton*)sender{
    
    
    [view removeFromSuperview];
    view=[[UIView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight)];
    view.backgroundColor=[UIColor clearColor];
    [self.view addSubview:view];
    
    UITapGestureRecognizer *singleFingerOne = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyBoad)];
    singleFingerOne.numberOfTouchesRequired = 1; //手指数
    singleFingerOne.numberOfTapsRequired = 1; //tap次数
    singleFingerOne.delegate = self;
    [view addGestureRecognizer:singleFingerOne];
    
    saveAccount=! saveAccount;
    
    if (!saveAccount) {
        diseview=[[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth/2-100, 0, 200, 50*content1.count)];
        [diseview setBackgroundImage:[UIImage imageNamed:@"kuang"] forState:UIControlStateNormal];
        [view addSubview:diseview];
        
        //        NSArray *array = @[@"全部货源",@"家居建材",@"厨房卫浴",@"居家家纺",@"家装灯饰",];
        //      NSArray *arraycol = @[[UIColor blackColor],[UIColor whiteColor],[UIColor whiteColor],[UIColor whiteColor],[UIColor whiteColor]];
        for (int i = 0; i<content1.count; i++) {
            
            UIButton *shanghubutton = [UIButton buttonWithType:UIButtonTypeCustom];
            shanghubutton.frame = CGRectMake(0, 5+50*i, 200, 50);
            
            shanghubutton.tag = i;
            [shanghubutton setTitle:[content1 objectAtIndex:i] forState:UIControlStateNormal];
            if ([self.titleLabel.text isEqualToString:[content1 objectAtIndex:i]]) {
                [shanghubutton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            }else{
                [shanghubutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            }
            
            shanghubutton.titleLabel.font=[UIFont systemFontOfSize:15];
            [shanghubutton addTarget:self action:@selector(shanghubuttonimage:) forControlEvents:UIControlEventTouchUpInside];
            [diseview addSubview:shanghubutton];
            
            UILabel*line=[[UILabel alloc]initWithFrame:CGRectMake(10, 5+50*i, 200-20, 0.35)];
            line.backgroundColor=luseColor;
            [diseview addSubview:line];
            
        }
        
    }else{
        
        [diseview removeFromSuperview];
        
        
    }
    
}
- (void)shanghubuttonimage:(UIButton *)button{
    
    
    [diseview removeFromSuperview];
    [view removeFromSuperview];
    [diseview removeFromSuperview];
    _sta=[NSString stringWithFormat:@"%@", code[button.tag]];
    [self setup];
    self.titleLabel.text = button.titleLabel.text;
    
}

-(void)addProduct:(UIButton*)sender{
    commdity.content=@"";
    DiscoverMCircleAddViewController *detailViewController = [[DiscoverMCircleAddViewController alloc] init];
    [self.navigationController pushViewController:detailViewController animated:YES];
   
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"商户圈";
    commdity=[HAODEsingleton shared];
    [self.tableView removeFromSuperview];
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor=zuiqianhuicolor;
    self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"MCircleListCell" bundle:nil] forCellReuseIdentifier:@"MCircleListCell"];
    [self.view addSubview:self.tableView];
    

    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     backColor,
                                                                     UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"Helvetica Neue" size:tetlefot],
                                                                     UITextAttributeFont,nil]];
   
    
    
    [self addFooter];
    [self addheader];
    code=[[NSMutableArray alloc]init];
    content1=[[NSMutableArray alloc]init];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:@"TopicType" forKey:@"optionName"];
    
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    
    
    [HttpRequest requestData:@"System/AppCodes" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            
            NSLog(@"====%@",severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                
                NSMutableArray* arrr=[[NSMutableArray alloc]init];
                arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
                for (NSDictionary* dicc in arrr )
                {
                    [code addObject:[dicc valueForKey:@"code"]];
                    [content1 addObject:[dicc valueForKey:@"content"]];
                    
                    
                }
                
                
            }else{
                [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                // [Global showTextHud:requestResultStr view:self.view];
                [Global showTextHudSub:requestResultStr view:self.view];
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:@"连接失败" view:self.view];
        }
        
    }];

    
    
}
- (void)setup{
    [noLabel removeFromSuperview];
    pageNumber=1;
    saveAccount=YES;
    amt=[[NSMutableArray alloc]init];
    detail=[[NSMutableArray alloc]init];
    provinceName=[[NSMutableArray alloc]init];
    status=[[NSMutableArray alloc]init];
    time=[[NSMutableArray alloc]init];
    reqId=[[NSMutableArray alloc]init];
    address=[[NSMutableArray alloc]init];
    userName=[[NSMutableArray alloc]init];
    cityName=[[NSMutableArray alloc]init];
    imageUrlFull=[[NSMutableArray alloc]init];
    
    NSUserDefaults *user1 = [NSUserDefaults standardUserDefaults];
    NSString* tokenId = [user1 objectForKey:@"tokenId"];
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:tokenId forKey:@"tokenId"];
    [params setValue:@"30" forKey:@"pageSize"];
    [params setValue:@"1" forKey:@"pageIndex"];
    [params setValue:_sta forKey:@"typeCode"];
    NSLog(@"-----%@",params);
//    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:20 view:self.view];
    [HttpRequest requestData:@"/Discover/MCircle/List" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            
            NSLog(@"-----%@",severDataDict.dataDict);
            
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
              
                
                [Global hideProgressHUDInternal:self.view];
                 TotalCount=[severDataDict.dataDict objectForKey:@"TotalCount"];
               
               
                
                arr=[severDataDict.dataDict objectForKey:@"DataLine"];
                [self setupCouponCommentView:severDataDict.dataDict];
                for (NSDictionary* dicc in arr )
                {
                  
                    [reqId addObject:[dicc valueForKey:@"fid"]];
                    
                    
                }
                 [noLabel removeFromSuperview];
                if (TotalCount.intValue==0) {
                    noLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 17)];
                    noLabel.text=@"无数据";
                    noLabel.textColor=[UIColor blackColor];
                    noLabel.textAlignment=NSTextAlignmentCenter;
                    noLabel.center=self.view.center;
                    [self.view addSubview:noLabel];
                   
                }

                
            }else{
                
                
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
                
                
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    
                    TheLoginViewController*detailViewController = [[TheLoginViewController alloc] init];
                    
                    [self.navigationController pushViewController:detailViewController animated:YES];
                    
                }
                
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:@"连接失败" view:self.view];
        }
        
    }];
    
   
    
}
//下拉刷新
- (void)addheader
{
    
    
    MJRefreshHeaderView* footer = [MJRefreshHeaderView header];
    footer.scrollView = self.tableView;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView* refreshView)
    {
        
        _sta=@"";
        [self setup];
        [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:2.0f];
        NSLog(@"%@--->正在刷新", refreshView.class);
    };
}



//上拉刷新
- (void)addFooter
{
    
    MJRefreshFooterView* footer = [MJRefreshFooterView footer];
    footer.scrollView = self.tableView;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView* refreshView)
    {
        if (TotalCount.intValue/30>=pageNumber) {
            pageNumber++;
            
            NSUserDefaults *user1 = [NSUserDefaults standardUserDefaults];
            NSString* tokenId = [user1 objectForKey:@"tokenId"];
            NSMutableDictionary *params = [NSMutableDictionary new];
            [params setValue:tokenId forKey:@"tokenId"];
            
            [params setValue:[NSString stringWithFormat:@"%d" ,pageNumber] forKey:@"pageIndex"];
            
            [params setValue:@"30" forKey:@"pageSize"];
           
            [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
            
            
            [HttpRequest requestData:@"/Discover/MCircle/List" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
                if (isSuccess) {
                    
                    NSLog(@"-----%@",severDataDict.dataDict);
                    
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                        [Global hideProgressHUDInternal:self.view];
                        
                        arr=[severDataDict.dataDict objectForKey:@"DataLine"];
                        if (arr.count>0) {
                            [allComment  removeAllObjects];
                            [reqId  removeAllObjects];
                            
                            
                            [self setupCouponCommentView:severDataDict.dataDict];
                            for (NSDictionary* dicc in arr )
                            {
                                
                                [reqId addObject:[dicc valueForKey:@"fid"]];
                                
                            }
                            
                        }
                        
                    }else{
                        
                        
                        NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                        [Global showTextHudSub:requestResultStr view:self.view];
                        
                        
                        if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                            
                            TheLoginViewController*detailViewController = [[TheLoginViewController alloc] init];
                            
                            [self.navigationController pushViewController:detailViewController animated:YES];
                            
                        }
                        
                    }
                    
                }
                else
                {
                    [Global hideProgressHUDInternal:self.view];
                    
                    [Global showTextHudSub:@"连接失败" view:self.view];
                }
                
            }];
        }else{
            
            NSString *requestResultStr=@"没有更多数据了！";
            // [Global showTextHud:requestResultStr view:self.view];
            [Global showTextHudSub:requestResultStr view:self.view];
            
            
        }
        
        
        
        [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:2.0f];
        NSLog(@"%@--->正在刷新", refreshView.class);
    };
    
}
- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    [self.tableView reloadData];
    [refreshView endRefreshing];
}


- (void)setupCouponCommentView:(NSDictionary *)dic{
    
    NSMutableArray *commentArray = [dic objectForKey:@"DataLine"];
    allComment = [NSMutableArray array];
    for (int i = 0; i<commentArray.count; i++) {
        
        NSMutableDictionary *dataDic = commentArray[i];
        if (![dataDic isKindOfClass:[NSNull class]]){
            
            NSArray *commentPicArray = [dataDic objectForKey:@"images"];
        
            MCirclemodel *cModel = [[MCirclemodel alloc]init];
            cModel.commentId = [dataDic objectForKey:@"fid"];
            cModel.userName = [dataDic objectForKey:@"createName"];
            cModel.isPraise = [dataDic objectForKey:@"isPraise"];
            cModel.commentCount =[NSString stringWithFormat:@"%@",  [dataDic objectForKey:@"commentCount"]];
            cModel.headImageUrl =[NSString stringWithFormat:@"%@",  [dataDic objectForKey:@"headImage"]];

            cModel.praiseCount =[NSString stringWithFormat:@"%@", [dataDic objectForKey:@"praiseCount"]];
            cModel.mcontent =[NSString stringWithFormat:@"%@", [dataDic objectForKey:@"mcontent"]];
            cModel.createdAt =[NSString stringWithFormat:@"%@ %@",[dataDic valueForKey:@"address"],[dataDic valueForKey:@"createDate"]];
            
            NSMutableArray *fakeCommentImagesSmall = [NSMutableArray array];
            NSMutableArray *fakeCommentImagesBig = [NSMutableArray array];
            for (NSDictionary *picDic in commentPicArray) {
                [fakeCommentImagesSmall addObject:[picDic objectForKey:@"imageUrlFull"]];
                [fakeCommentImagesBig addObject:[picDic objectForKey:@"imageUrlFull"]];
            }
            cModel.imagePicSmall = fakeCommentImagesSmall;
            cModel.imagePicBig = fakeCommentImagesBig;
            [allComment addObject:cModel];
        }
    }
    [self.view addSubview:self.tableView];
    [self.tableView reloadData];
}



#pragma mark - TableView dataSource && delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return allComment.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
       return [MCircleListCell cellHeight:allComment[indexPath.row]];
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *identifier = @"MCircleListCell";
    MCircleListCell *cell = (MCircleListCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"MCircleListCell" owner:self options:nil][0];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    MCirclemodel *obj = allComment[indexPath.row];
    cell.comment = obj;
  
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    commdity.reqId=reqId[indexPath.row];
  
    DiscoverMCircleDetailViewController* store=[[DiscoverMCircleDetailViewController alloc]init];
    
    [self.navigationController pushViewController:store animated:YES];
    
    
}


-(NSString *)ret32bitString:(NSInteger)i

{
    
    char data[i];
    
    for (int x=0;x<i;data[x++] = (char)('A' + (arc4random_uniform(26))));
    
    return [[NSString alloc] initWithBytes:data length:i encoding:NSUTF8StringEncoding];
    
}
-(int)getRandomNumber:(int)from to:(int)to

{
    
    return (int)(from + (arc4random() % (to - from + 1)));
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
